using UnityEngine;
using System.Collections;

public struct AnimationEventFrame
{
	public int KeyFrame;
	public string MethodName;
}

[RequireComponent(typeof(SpriteRenderer))]
public class AnimationFrames : MonoBehaviour
{
	public float timeFrame;
	public int keyStart;
	public int keyEnd;

	int currentKeyFrame;
	SpriteRenderer render;
	Sprite[] frames;
	float elapsedTime;
	bool isEnable;

	void Awake()
	{
		render = GetComponent<SpriteRenderer> ();
		frames = new Sprite[0];
	}

	public void createAnimation(string _path, float _timeFrame)
	{
		Resources.UnloadUnusedAssets ();
		frames = Resources.LoadAll<Sprite> (_path);

		if(_timeFrame != -1)
			timeFrame = _timeFrame / frames.Length;

		keyStart = currentKeyFrame = 0;
		keyEnd = frames.Length - 1;

		if (frames.Length > 0)
		{
			render.sprite = frames[currentKeyFrame];
			isEnable = true;
		}
	}

	public void createAnimation(string _path = "", int _frameStart = 0, int _keyStart = 0, int _frameEnd = -1)
	{
		Resources.UnloadUnusedAssets ();
		frames = Resources.LoadAll<Sprite>(_path);

		//frame start
		if (_frameStart < 0 || _frameStart > frames.Length - 1)
		{
			keyStart = 0;
		}
		else
			keyStart = _frameStart;

		//frame end
		if (_frameEnd == -1 || _frameEnd > frames.Length - 1)
		{
			keyEnd = frames.Length - 1;
		}
		else
			keyEnd = _frameEnd;

		//key frame
		if (_keyStart < keyStart || _keyStart > keyEnd)
		{
			currentKeyFrame = keyStart;
		}
		else
			currentKeyFrame = _keyStart;
		
		if (frames.Length > 0)
		{
			render.sprite = frames[currentKeyFrame];
			isEnable = true;
		}
	}
	
	void Update()
	{
		if (frames.Length > 0 && isEnable == true)
		{
			elapsedTime += Time.deltaTime;

			//Next frame
			if (elapsedTime >= timeFrame)
			{
				if (currentKeyFrame >= keyEnd)
				{
					currentKeyFrame = keyStart;
				}
				else
				{
					currentKeyFrame++;
				}
				render.sprite = frames[currentKeyFrame];
				elapsedTime -= timeFrame;
			}
		}
	}
	
	public void Reset()
	{
		currentKeyFrame = keyStart;
		render.sprite = frames[currentKeyFrame];
		elapsedTime = 0;
	}
	
	public void Pause()
	{
		if(isEnable)
			isEnable = false;
	}
	
	public void Play()
	{
		if(!isEnable)
			isEnable = true;
	}
	
	public int Count 
	{ 
		get 
		{ 
			return (keyEnd - keyStart) + 1;
		}
	}
	
	//Index of frame hien tai, bat dau tu 0
	public int KeyIndex 
	{ 
		get
		{ 
			return currentKeyFrame - keyStart;
		}
	}
	
	public float TotalTimeAnimation 
	{ 
		get 
		{ 
			return timeFrame * ((keyEnd - keyStart) + 1);
		}
	}
	
	//Dung neu ket thuc chuoi frame
	public bool EndOfFrames 
	{ 
		get 
		{ 
			if (currentKeyFrame == keyEnd) 
				return true; 
			else 
				return false;
		}
	}
	
	//Thay doi key frame
	public void changeFrame(int frameStart = 0, int frameEnd = -1)
	{
		currentKeyFrame = keyStart = frameStart;
		render.sprite = frames[currentKeyFrame];
		if (frameEnd == -1 || frameEnd >= frames.Length)
		{
			keyEnd = frames.Length - 1;
		}
		else
			keyEnd = frameEnd;
		
	}
}

